<?php
// +----------------------------------------------------------------------
// | HkCms 用户验证规则
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\content\validate;

use think\Validate;
use think\Db;

class Category extends Validate
{
    protected $rule = [
        'catname' => 'require|max:25',
        // 'catdir' => 'require|checkCatdir',
        // 'catdir' => 'require|unique:category',
        'catdir' => 'require|max:25|checkCatdir',
        'setting' => 'checkSetting',
        'type' => 'in:0,1,2',
    ];

    protected $message  =   [
        'catname.require' => '栏目名称不能为空！',
        'catdir.require' => '英文目录不能为空！',
        'catname.max' => '栏目名称太长',
        'catdir.max' => '英文目录太长！',
        // 'catdir.checkCatdir' => '目录名称已存在！',
        'catdir.unique' => '目录名称已存在！',
        'setting.checkSetting' => 'Setting配置信息有误！',
        'modelid.unique' => '所属模型不能为空！',
    ];


    // protected $scene = [
    //     'edit'  =>  ['catname','catdir' => 'require|max:25|checkCatdir',],
    // ];

    /**
     * 验证setting配置信息
     * @param type $setting
     * @return boolean
     */
    protected  function checkSetting($value,$rule,$data) 
    {

        $type = (int) isset($data['type'])?$data['type']:input('type');

        if ($type == 2) {

            return true;
        }

        if (!$value) {

            return true;
        }

        $setting = unserialize($value);

        if ((!$setting['category_ruleid'] || !$setting['category_ruleid']) && (int)$type != 2) {

            return 'Setting配置信息有误';
        }

        return true;
    }

    /**
     * 检查目录是否存在
     */
    protected function checkCatdir($value,$rule,$data) 
    {

        $find = Db::name('category')->where(function ($query) use ($data){

            $query->where('parentid', 0)->where('catdir', $data['catdir']);

        })->whereOr(function ($query) use ($data){

            $query->where('parentid', $data['parentid'])->where('catdir', $data['catdir']);
        })->find();

        if ($find) {

            if ( isset($find['catid']) ) {
                if ( $find['catid'] == input('catid') ) {

                    return true;
                }
            }

            return '英文目录重复';
        }

        return true;
    }
    

}